//
//  WithdrawCashViewController.m
//  Exchange
//
//  Created by 张庆勇 on 2018/8/1.
//  Copyright © 2018年 张庆勇. All rights reserved.
//

#import "WithdrawCashViewController.h"
#import "AssetRecordsViewController.h"
#import "ChooseWithdrawAddressListViewController.h"
#import "WithdrawCustomAlert.h"
#import "WithdrawViewCustomAlertVC.h"
#import "CheckVersionAlearView.h"
#import "CapitalPasswordViewController.h"
@interface WithdrawCashViewController ()<UITextFieldDelegate>
@property (nonatomic,strong)NSString * addreassid;
@property (nonatomic,strong)NSString * withdraw_fee;
@property (nonatomic,strong)NSMutableArray * nameArray;
@property (nonatomic,strong)NSString * format;//精度
@property (nonatomic,strong)NSString * withdraw_min;//最小d提笔
@property (nonatomic,strong)NSString * withdraw_max;//最大d提笔
@end

@implementation WithdrawCashViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self customUI];
    [self getbalance];
    for (AssetsModle *modle in _dataArray) {
        [self.nameArray addObject:modle.name];
    }
    self.view.backgroundColor = MAINBLACKCOLOR;
    [_remakeField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem RightitemWithImageNamed:@"" title:Localized(@"Asset_Currency_record") target:self action:@selector(Record)];
    if (_modle.has_memo.integerValue ==0)
    {
        _bgView4.hidden = YES;
        _tibiTitle.hidden = YES;
        [self performSelector:@selector(modifyConstant) withObject:nil afterDelay:0.1];//延迟加载,执行
    }
}
- (NSMutableArray *)nameArray
{
    if (!_nameArray) {
        _nameArray = [[NSMutableArray alloc] init];
    }
    return _nameArray;
}
- (void)refushData:(NSString *)number
{
    if ([NSString isEmptyString:number]) {
        number = @"0";
    }
    NSDecimalNumber*jian1 = [NSDecimalNumber decimalNumberWithString:number];
    NSDecimalNumber*jian2 = [NSDecimalNumber decimalNumberWithString:_withdraw_fee];
    NSDecimalNumber*jian = [jian1 decimalNumberBySubtracting:jian2];
    if (jian.floatValue <0)
    {
        NSString * str = [NSString stringWithFormat:self.format,@"0"];
        _accountsNum.text = [NSString stringWithFormat:@"%@ %@",str,_modle.name];
    }else
    {
   
        _accountsNum.text = [NSString stringWithFormat:@"%@ %@",jian,_modle.name];
    }
   
}
- (void)modifyConstant
{
     self.top.constant -=84;
}
-(void)textFieldDidChange :(UITextField *)TextField{
    
     [self refushData:TextField.text];
}
- (void)customUI
{
    _titleWithdraw.text = [NSString stringWithFormat:@"%@ %@",_modle.name,Localized(@"Asset_Withdraw")];
    _availTitleLable.text = Localized(@"transaction_available");
    _frozenTitleLable.text = Localized(@"Asset_Frozen");
    _totalTitleLable.text = [NSString stringWithFormat:Localized(@"Asset_Compromise"),[EXUserManager getValuationMethod]];
    _addreasTitleLable.text = Localized(@"my_Currency_address");
    _remakeTitleLable.text = Localized(@"Asset_Amount_of_money");
    _tibiTitle.text = Localized(@"Address_title");
    [_allButton setTitle:Localized(@"Asset_whole") forState:0];
    _feeTitleLable.text = Localized(@"Asset_Service_Charge");
    _accountTitleLable.text = Localized(@"Asset_Number_of_accounts");
     [_button setTitle:Localized(@"Asset_Withdraw") forState:0];
    
    _accountsNum.text  = [NSString stringWithFormat:@"0.00%@",_modle.name];
    _feeField.text = _modle.withdraw_fee;
     _name.text = _modle.name;
    KViewRadius(self.button, 2);
    _bgView.backgroundColor = MainBGCOLOR;
    _bgView1.backgroundColor = textFieldColor;
    _bgView2.backgroundColor = textFieldColor;
    _bgView3.backgroundColor = textFieldColor;
    _bgView4.backgroundColor = textFieldColor;
    _name.textColor = MAINTITLECOLOR;
    _titleWithdraw.textColor = MAINTITLECOLOR;
    _available.textColor = MAINTITLECOLOR;
    _Frozen.textColor = MAINTITLECOLOR;
    _Total.textColor = MAINTITLECOLOR;
    _addreasField.textColor = MAINTITLECOLOR;
    _remakeField.textColor = MAINTITLECOLOR;
    _accountsNum.textColor = MAINTITLECOLOR;
    _feeField.textColor = MAINTITLECOLOR;
    _available.method = UILabelCountingMethodEaseOutBounce;
    _remakeField.keyboardType = UIKeyboardTypeDecimalPad;
//    _available.format =@"%.4f";
    _Frozen.method = UILabelCountingMethodEaseOutBounce;
//    _Frozen.format =@"%.4f";
    _Total.method = UILabelCountingMethodEaseOutBounce;
    _Total.format =@"%.2f";
    [self initTextField:_addreasField placeholder:Localized(@"Asset_Confirmation_addreass")];
    [self initTextField:_remakeField placeholder:Localized(@"Asset_Confirmation_num")];
    [self initTextField:_feeField placeholder:@""];
    [self initTextField:_tibiTitleField placeholder:Localized(@"Address_title_msg")];
    [self initstyte];
    if ([EXUnit isHideCurrencyPrice]) {
        _totalTitleLable.hidden = YES;
        _Total.hidden = YES;
    }
    
}
- (void)initTextField:(UITextField *)textField placeholder:(NSString *)placeholder
{
    textField.placeholder = placeholder;
    [textField setValue:AutoFont(13) forKeyPath:@"_placeholderLabel.font"];
    [textField setValue:textFieldPCOLOR forKeyPath:@"_placeholderLabel.textColor"];
    textField.tintColor = TABTITLECOLOR;
    textField.textColor = MAINTITLECOLOR;
   
    textField.delegate = self;
}
- (void)initstyte
{
    RACSignal*addreasSignal=[_addreasField.rac_textSignal map:^id(NSString* value) {
        return  @(value.length>0);
    }];
    RACSignal*remakeSignal=[_remakeField.rac_textSignal map:^id(NSString* value) {
        return @(value.length>0);
    }];
    RACSignal*loginSignal=[RACSignal combineLatest:@[addreasSignal,remakeSignal] reduce:^id(NSNumber*addreasValid,NSNumber*remakeValid){
        return @([addreasValid boolValue]&&[remakeValid boolValue]);
    }];
    WeakSelf
    [loginSignal subscribeNext:^(NSNumber* x) {
        if ([x boolValue]) {
            weakSelf.button.enabled=YES;
            weakSelf.button.alpha = 1;
        }else{
            weakSelf.button.enabled=NO;
            weakSelf.button.alpha = 0.5;
            
        }
    }];
}
//提币记录
- (void)Record
{
    AssetRecordsViewController * asset = [[AssetRecordsViewController alloc] init];
    asset.title = Localized(@"Asset_records");
    asset.index = 1;
    asset.dataArray = _nameArray;
    [self.navigationController pushViewController:asset animated:YES];
}
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    if (textField ==_feeField ||textField == _addreasField) {
        return NO;
    }
    return YES;
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (IBAction)withdrawButton:(UIButton *)sender {
     float accountsNumber =   _remakeField.text.floatValue -  _modle.withdraw_fee.floatValue;
    if (accountsNumber <=0) {
         [self axcBasePopUpWarningAlertViewWithMessage:Localized(@"Asset_amount_message") view:kWindow];
        return;
    }
     NSDecimalNumber*jianfa1 = [NSDecimalNumber decimalNumberWithString:_remakeField.text];
     NSDecimalNumber*jianfa2 = [NSDecimalNumber decimalNumberWithString:self.available.text];
     NSComparisonResult result_clearrate_float = [jianfa1 compare:jianfa2];
    if (result_clearrate_float==NSOrderedDescending )
    {
        [self axcBasePopUpWarningAlertViewWithMessage:@"余额不足" view:kWindow];
        return;
        
    }
    NSDecimalNumber * withdraw_min = [NSDecimalNumber decimalNumberWithString:_withdraw_min];
    NSDecimalNumber*tibiNum = [NSDecimalNumber decimalNumberWithString:_remakeField.text];
    NSComparisonResult result = [withdraw_min compare:tibiNum];
    if (result==NSOrderedDescending )
    {
        [self axcBasePopUpWarningAlertViewWithMessage:[NSString stringWithFormat:Localized(@"tibi_zhishao_message"),_withdraw_min] view:kWindow];
        return;
        
    }
    
    [_remakeField resignFirstResponder];
    
    if ([EXUserManager personalData].withdraw_password_set) {
        WithdrawViewCustomAlertVC * custom = [[WithdrawViewCustomAlertVC alloc] initWithCustomContentViewClass:@"WithdrawCustomAlert" delegate:nil];
        custom.direction = FromBottom;
        [custom show];
        WithdrawCustomAlert *aleatView = (WithdrawCustomAlert *)custom.contentView;
        aleatView.type = @"7";
        aleatView.cancelBlock = ^{
            [custom dismiss];
        };
            WeakSelf
        WeakObject(aleatView)
        [aleatView.okButton add_BtnClickHandler:^(NSInteger tag) {
            
            if (![NSString isEmptyString:weakaleatView.emailField.text])
            {
                if (![EXUnit CodeissSixplace:weakaleatView.emailField.text]) {
                    [EXUnit showMessage:Localized(@"VerificationMessage")];
                    [weakaleatView.okButton stopAnimation];
                    return ;
                }
            }
            if (![NSString isEmptyString:weakaleatView.phoneField.text])
            {
                if (![EXUnit CodeissSixplace:weakaleatView.phoneField.text]) {
                    [EXUnit showMessage:Localized(@"VerificationMessage")];
                    [weakaleatView.okButton stopAnimation];
                     ;
                }
            }
            if (![EXUnit judgePassWordLegal:weakaleatView.capitalField.text])
            {
                [self axcBasePopUpWarningAlertViewWithMessage:Localized(@"login_Illegal_password") view:kWindow];
                return;
            }
            weakaleatView.okButton.userInteractionEnabled = NO;//不可点击
            NSDictionary * dic = @{@"asset":weakSelf.modle.name,
                                   @"address_id":weakSelf.addreassid,
                                   @"amount":weakSelf.remakeField.text,
                                   @"password":[NSString isEmptyString:weakaleatView.capitalField.text]?@"":weakaleatView.capitalField.text,
                                   @"sms_code":[NSString isEmptyString:weakaleatView.phoneField.text]?@"":weakaleatView.phoneField.text,
                                   @"email_code":[NSString isEmptyString:weakaleatView.emailField.text]?@"":weakaleatView.emailField.text,
                                   @"two_step_code":[NSString isEmptyString:weakaleatView.gooldField.text]?@"":weakaleatView.gooldField.text,};
            
            [self POSTWithHost:@"" path:userwithdraw param:dic cache:NO completed:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                if ([responseObject[@"code"] integerValue]==0)//成功
                {
                    
                    weakaleatView.okButton.userInteractionEnabled = YES;
                    [custom dismiss];
                    [weakSelf axcBasePopUpWarningAlertViewWithMessage:responseObject[@"message"] view:kWindow];
                    weakSelf.remakeField.text = @"";
                    [self refushData:@""];
                    [self getbalance];
                    
                    
                    
                }else
                {
                    [weakSelf axcBasePopUpWarningAlertViewWithMessage:responseObject[@"message"] view:kWindow];
                    
                }
                [weakaleatView.okButton stopAnimation];
                return ;
            } error:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                [weakaleatView.okButton stopAnimation];
            }];
            
        }];
    }else
    {
        CheckVersionAlearView * aleartVC = [[CheckVersionAlearView alloc] initWithmessage:Localized(@"Asset_capital_message")
                                                                                 titleStr:Localized(@"C2C_Reminder")
                                                                                  openUrl:@""
                                                                                  confirm:Localized(@"transaction_OK")
                                                                                   cancel:Localized(@"transaction_cancel")
                                                                                    state:2
                                                                            RechargeBlock:^
                                            {
                                                
                                                CapitalPasswordViewController *  Capitalpass  = [[CapitalPasswordViewController alloc] init];
                                                Capitalpass.isEdit = NO;
                                                Capitalpass.title = [EXUserManager personalData].withdraw_password_set?Localized(@"Security_fund_password"):Localized(@"Security_Set_funds_password");
                                                [self.navigationController pushViewController:Capitalpass animated:YES];
                                                
                                            }];
        aleartVC.animationStyle = LXASAnimationLeftShake;
        [aleartVC showLXAlertView];
        
    }
}
- (void)getbalance
{
    WeakSelf
    [self GETWithHost:@"" path:Userassets param:@{} cache:NO completed:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if ([responseObject[@"code"] integerValue]==0)//成功
        {
            NSDictionary *dataDic  = responseObject[@"result"];
            double totalprofit;
            NSArray * keyArray = dataDic.allKeys;
           
            for (NSString *str in keyArray) {
                NSDictionary *dic = dataDic[str];
                AssetsModle * modle = [[AssetsModle alloc] init];
                modle.name =str;
                modle.available =dic[@"available"];
                modle.c2c_freeze =dic[@"c2c_freeze"];
                modle.freeze =dic[@"freeze"];
                modle.has_memo = dic[@"has_memo"];
                modle.recharge_status =dic[@"recharge_status"];
                modle.trade_status =dic[@"trade_status"];
                modle.withdraw_fee =dic[@"withdraw_fee"];
                modle.other_freeze =dic[@"other_freeze"];
                modle.precision =dic[@"precision"];
                modle.withdraw_min = dic[@"withdraw_min"];
                modle.withdraw_max = dic[@"withdraw_max"];
                totalprofit = modle.available.floatValue + modle.c2c_freeze.floatValue + modle.freeze.floatValue + modle.withdraw_freeze.floatValue +modle.other_freeze.floatValue;
                NSString * toalstr = [EXUnit getCapitalPriceNoUnitWithName:modle.name Price:[NSString stringWithFormat:@"%f",totalprofit]];
                modle.totalprofit = toalstr.doubleValue;
            
                if ([str isEqualToString:weakSelf.modle.name])
                {
                    weakSelf.format = [NSString stringWithFormat:@"%%.%@f",modle.precision];
                    weakSelf.available.format =weakSelf.format;
                    weakSelf.Frozen.format =weakSelf.format;
                    weakSelf.available.text = modle.available;
                    weakSelf.withdraw_min =  modle.withdraw_min;
                    weakSelf.withdraw_max =  modle.withdraw_max;
                    [weakSelf.Frozen countFrom:0 to:modle.freeze.floatValue+modle.other_freeze.floatValue withDuration:1];
                    [weakSelf.Total countFrom:0 to:modle.totalprofit withDuration:1];
                    weakSelf.withdraw_fee = modle.withdraw_fee;
                    weakSelf.feeField.text = modle.withdraw_fee;
                  break;
                }
            }
            
        }else
        {
            [self axcBasePopUpWarningAlertViewWithMessage:responseObject[@"message"] view:kWindow];
        }
    } error:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}
- (IBAction)allButton:(UIButton *)sender {
    [self refushData:self.available.text];
    _remakeField.text =  self.available.text;
    [self initstyte];
   
}

- (IBAction)chooseAddress:(UIButton *)sender {
   [self chooseaddress];
}
- (IBAction)chooseAddressTitle:(UIButton *)sender {
    [self chooseaddress];
}
- (void)chooseaddress
{
    ChooseWithdrawAddressListViewController * chooseAddressVC = [[ChooseWithdrawAddressListViewController alloc] init];
    chooseAddressVC.title = Localized(@"Asset_Select_address");
    chooseAddressVC.modle = _modle;
    [self.navigationController pushViewController:chooseAddressVC animated:YES];
    WeakSelf
    chooseAddressVC.addRelastblock = ^(NSString *addreass, NSString *addressId) {
        NSArray * array = [addreass componentsSeparatedByString:@":"];
        if (array.count>1)
        {
           weakSelf.addreasField.text = array[0];
            weakSelf.tibiTitleField.text = array[1];
        }else
        {
           weakSelf.addreasField.text = array[0];
            
        }
        weakSelf.addreassid = addressId;
        [self initstyte];
    };
}
@end
